package distributed.lock.factory;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;

/**
 * @comment
 * @date 2015年11月10日 下午3:09:09
 * @author zhouxiao
 * @qq 772716714
 * @version 1.0
 */
public class ZookeeperFactory extends AbstractZookeeper {
	/**
	 * 创建节点
	 * 
	 * @param path
	 * @param data
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public void create(String path, String data) throws KeeperException, InterruptedException {
		this.zooKeeper.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
	}

	/**
	 * 获取节点数据
	 * 
	 * @param path
	 * @return
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public String getData(String path) throws KeeperException, InterruptedException {
		return new String(this.zooKeeper.getData(path, false, null));
	}

	/**
	 * 修改节点数据
	 * 
	 * @param path
	 * @param data
	 * @param version
	 * @return
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public Stat setDate(String path, String data, int version) throws KeeperException, InterruptedException {
		return this.zooKeeper.setData(path, data.getBytes(), version);
	}

	/**
	 * 删除节点
	 * 
	 * @param path
	 * @throws InterruptedException
	 * @throws KeeperException
	 */
	public void delete(String path) throws InterruptedException, KeeperException {
		this.zooKeeper.delete(path,-1);
	}

	/**
	 * 节点是否存在
	 * 
	 * @param path
	 * @return
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public boolean exists(String path) throws KeeperException, InterruptedException {
		Stat stat = this.zooKeeper.exists(path, null);
		return stat != null;
	}
}
